import React, { useState, useEffect } from 'react';
import { IkFind, ck_float, Ret, CkValue, useCheck, useForm, IkInput, WaitUmd, MainView, PanelTitle, IkSelect, Btn,
    is_empty, urlTb, obj_empty, cline, obj_str, useCmd, ck_empty, loc } from 'sui';
import { tp_name } from './cmd';

const Hand = ({ para, cur, hreturn, main }) => {
    const [lst_dsn, lstDsn] = useState();
    const [lst_wsn, lstWsn] = useState();
    const [lst_fsn, lstFsn] = useState();
    const [cur_dsn, setDsn] = useState();
    const [value, setValue] = useState();
    const form = useForm(setValue);
    const [open, setOpen, hcheck] = useCheck();
    const umd = useCmd(null, "hand");

    useEffect(() => {
        setDsn("");

        let db = null;
        let sta = null;

        if (para) {
            db = para["cell"];
            sta = para["station"];
        }

        if (!is_empty(db)) {
            const tmp = db.map(d => {
                return {id: d.sn, sn: d.sn, name: `${d.name} (${d.sn})`};
            });

            lstDsn(tmp);
        }

        if (!is_empty(sta)) {
            const tmp = sta.map(d => {
                return {id: d.sn, sn: d.sn, name: d.name};
            });

            lstWsn(tmp);
        }

        if (obj_empty(cur)) {
            setValue(null);
            return;
        }

        setValue({
            sn: obj_str(cur, "sn"),
            name: obj_str(cur, "name"),
            tp: obj_str(cur, "tp"),
            num: obj_str(cur, "num"),
            ucl: obj_str(cur, "ucl"),
            cl: obj_str(cur, "cl"),
            lcl: obj_str(cur, "lcl"),
            dsn: obj_str(cur, "dsn"),
            fsn: obj_str(cur, "fsn"),
            wsn: obj_str(cur, "wsn"),
            usl: obj_str(cur, "usl"),
            sl: obj_str(cur, "sl"),
            lsl: obj_str(cur, "lsl"),
        });
    }, [cur, para]);

    useEffect(() => {
        let db = null;
        if (para) {
            db = para["cell"];
        }

        if (is_empty(db)) {
            lstFsn(null);
            setDsn("");
            return;
        }

        const dsn = obj_str(value, "dsn");
        if (cur_dsn === dsn) {
            return;
        }

        const f = db.find(d => d.sn === dsn);
        if (!f) {
            lstFsn(null);
            setDsn("");
            return;
        }

        setDsn(dsn);

        const keym = f["keym"];
        const keyd = f["keyd"];
        if (is_empty(keym)) {
            lstFsn(null);
            return;
        }

        urlTb(null, "field", {n: dsn},
            r => {
                const set = new Set();
                set.add("dtp");

                r[dsn].forEach(d => set.add(d));

                const tmp = [];
                keym.forEach((d, i) => {
                    if (!set.has(d)) {
                        return;
                    }

                    tmp.push({id: d, sn: d, name: `${keyd[i]} (${d})`});
                });

                lstFsn(tmp);
            },
            e => {
                const tmp = [];
                keym.forEach((d, i) => tmp.push({id: d, sn: d, name: `${keyd[i]} (${d})`}));

                lstFsn(tmp);
            });
    }, [para, cur_dsn, value]);

    const hdone = () => {
        const ck = {
            sn: (v) => {
                let e = ck_empty(v, "SN");
                if (e) {
                    return e;
                }

                if (is_empty(main)) {
                    return null;
                }

                let ft = main;
                if (!obj_empty(cur)) {
                    const tmp = obj_str(cur, "sn");
                    ft = main.filter(d => d.sn !== tmp);
                }

                const f = ft.find(d => d.sn === v);
                if (f) {
                    return "SN" + loc("mg_152");
                }

                return null;
            },
            name: (v) => ck_empty(v, loc("cmd_097")),
            wsn: (v) => ck_empty(v, loc("product_14")),
            tp: (v) => ck_empty(v, loc("mg_007")),
            num: (v) => ck_float(v, loc("product_38")),
            dsn: (v) => ck_empty(v, `${loc("mg_163")}${loc("db_020")}`),
            fsn: (v) => ck_empty(v, loc("mg_163")),
            usl: (v) => {
                if (v) {
                    return ck_float(v, "USL");
                }

                return null;
            },
            sl: (v) => {
                if (v) {
                    return ck_float(v, "SL");
                }

                return null;
            },
            lsl: (v) => {
                if (v) {
                    return ck_float(v, "LSL");
                }

                return null;
            },
            ucl: (v) => {
                if (v) {
                    return ck_float(v, "UCL");
                }

                return null;
            },
            cl: (v) => {
                if (v) {
                    return ck_float(v, "CL");
                }

                return null;
            },
            lcl: (v) => {
                if (v) {
                    return ck_float(v, "LCL");
                }

                return null;
            },
        };

        if (!form.hcheck(ck, value)) {
            return;
        }

        umd.startWait();

        const dsn = obj_str(value, "dsn");
        const fsn = obj_str(value, "fsn");

        const val = [
            {k: "sn", "v": obj_str(value, "sn")},
            {k: "wsn", "v": obj_str(value, "wsn")},
            {k: "name", "v": obj_str(value, "name")},
            {k: "num", "v": obj_str(value, "num")},
            {k: "tp", "v": obj_str(value, "tp")},
            {k: "dsn", "v": dsn},
            {k: "fsn", "v": fsn},
        ];

        const cus = ["lcl", "cl", "ucl", "lsl", "sl", "usl"];

        cus.forEach(d => {
            const t = obj_str(value, d);
            val.push({k: d, v: t});
        });

        let cmd = {};

        if (cur) {
            cmd["m"] = [{
                u: obj_str(cur, "uid"),
                v: val,
            }];
        }
        else {
            cmd["a"] = [{
                u: cline(),
                n: "spc",
                v: [val]
            }];
        }

            /*
        urlM(null, cmd,
            r => {
                umd.endWait();
                hreturn(true);
            },
            e => umd.setWront(loc("mg_039")));
            */
    };

    const ckdes = {
        sn: "SN",
    };

    const lst_tp = [
        {id: "xbar", des: tp_name("xbar")},
        {id: "np", des: tp_name("np")},
        {id: "c", des: tp_name("c")},
        {id: "p", des: tp_name("p")},
        {id: "u", des: tp_name("u")},
    ];

    const Right = () => (
        <>
            <Btn name="done" className="mr-4" hcmd={() => hcheck(value, ckdes, hdone)} color="green">{loc("nui_26")}</Btn>
            <Ret hcmd={() => hreturn(false)}/>
        </>
    );

    const xbarExt = () => {
        const tp = obj_str(value, "tp");
        if (tp !== "xbar") {
            return null;
        }

        return (
            <>
                <IkInput label="USL" name="usl" form={form} value={value} className="mr-4" width="w-24"/>
                <IkInput label="SL" name="sl" form={form} value={value} className="mr-4" width="w-24"/>
                <IkInput label="LSL" name="lsl" form={form} value={value} className="mr-4" width="w-24"/>
            </>
        );
    };

    return (
        <MainView>
            <PanelTitle left={loc("z_45")} right={<Right/>} cl="gray"/>
            <div className="ml-4">
                <div className="mt-3 flex flex-row">
                    <IkInput label={ckdes.sn} name="sn" form={form} value={value}/>
                    <IkInput label={loc("cmd_097")} name="name" form={form} value={value} className="mx-4"/>
                    <IkSelect className="mt-2 mr-4" label={loc("mg_007")} name="tp" form={form} value={value} lst={lst_tp}/>
                    <IkInput label={loc("product_38")} name="num" form={form} value={value}/>
                </div>
                <div className="mt-3 flex flex-row">
                    <IkFind className="mr-4" name="dsn" value={value} form={form} label={loc("mg_163")} lst={lst_dsn}/>
                    <IkFind className="mr-4" label={`${loc("mg_163")}${loc("db_020")}`} name="fsn" form={form} value={value} lst={lst_fsn}/>
                    <IkFind className="mr-4" name="wsn" value={value} form={form} label={loc("product_14")} lst={lst_wsn}/>
                </div>
                <div msg={loc("mg_130")}/>
                <div className="flex flex-row flex-wrap">
                    {xbarExt()}
                </div>
                <div className="flex flex-row flex-wrap">
                    <IkInput label="UCL" name="ucl" form={form} value={value} className="mr-4" width="w-24"/>
                    <IkInput label="CL" name="cl" form={form} value={value} className="mr-4" width="w-24"/>
                    <IkInput label="LCL" name="lcl" form={form} value={value} className="mr-4" width="w-24"/>
                </div>
            </div>
            <CkValue setOpen={setOpen} open={open} value={value} des={ckdes} setValue={setValue} hcmd={hdone}/>
            <WaitUmd umd={umd}/>
        </MainView>
    );
};

export {Hand};
